const koaServerHttpProxy = require('koa-server-http-proxy');
const koaStatic = require('koa-static');
const koaSession = require('koa-session');
const {
    URL
} = require('url');
const { URLSearchParams } = require('url')
const { strDec } = require('./des');

const sessionConfig = {
    maxAge: undefined
};

function parseBody(res) {
    return new Promise((resolve, reject) => {
        let body = [];
        res.on('data', function (chunk) {
            body.push(chunk);
        });
        res.on('end', function () {
            body = Buffer.concat(body).toString();
            resolve(body);
        });
        res.on('error', reject)
    })
}

// proxyRes: 代理返回给前端值
// req: 代理请求 res: 代理返回
function onProxyRes(proxyRes, req, res) {

    if (proxyRes.statusCode === 301 || proxyRes.statusCode === 302) {
        let location = proxyRes.headers.location;
        if (location.startsWith("http")) {
            let url = new URL(location);
            proxyRes.headers.location = `${url.pathname}${url.search}${url.hash}`
        }
        return;
    }

    if (req.url.startsWith('/infoplus/interface/render') && req.method.toUpperCase() === "POST") {
        parseBody(proxyRes).then(data => {
            let dataObj = JSON.parse(data);
            Object.assign(dataObj.entities[0].data, {
                fieldSTQKbrstzk1: "1",
                fieldYQJLsfjcqtbl: "2",
                fieldJKMsfwlm: "1",
                fieldCXXXsftjhb: "2",
                fieldCNS: true
            })
            res.statusCode = 200;
            res.end(JSON.stringify(dataObj));
        })
        return;
    }

}

let proxyConfig = new Map([
    // 广大登录
    [
        ['/cas'], {
            target: 'https://newcas.gzhu.edu.cn',
            changeOrigin: true
        }
    ],

    // 广大打卡
    [
        ['/infoplus/interface/render'], {
            target: 'https://yqtb.gzhu.edu.cn',
            changeOrigin: true,
            selfHandleResponse: true
        }
    ],

    [
        ['/infoplus', '/taskcenter'], {
            target: 'https://yqtb.gzhu.edu.cn',
            changeOrigin: true
        }
    ]
])

function init(app) {

    app.keys = ['mrliu'];
    app.use(koaSession(sessionConfig, app));

    app.use(async (ctx, next) => {
        // let userInfo = ctx.session.userInfo;
        // if (!!userInfo) {
        //     ctx.session.userInfo = {}
        // } else { // 拥有userInfo不管什么页面完全自动登录
            
        // }
       
        // 登录设置login
        if (ctx.path.startsWith('/cas/login') && ctx.method.toUpperCase() === "POST") {
            parseBody(ctx.req).then(data => {
                let userData = new URLSearchParams(data);
                let userStr = strDec(userData.get("rsa"), '1', '2', '3'),
                    ul = Number(userData.get("ul")) || 0,
                    pl = Number(userData.get("pl")) || 0;
                let userInfo = {
                    username: userStr.substring(0, ul),
                    password: userStr.substring(ul, ul + pl),
                    isAutoClick: userData.get("isAutoClick") === "true"
                }
                // ctx.session.userInfo = userInfo;
                console.log("userInfo", userInfo);
            })
        }
        await next();
    })

    app.use(koaStatic(__dirname + '/page', {
        extensions: [".html"]
    }))

    proxyConfig.forEach((value, paths) =>
        paths.forEach(path =>
            app.use(koaServerHttpProxy(path, Object.assign({
                onProxyRes: onProxyRes
            }, value)))
        )
    );
}

module.exports = {
    init
}